package com.example.templateapp.widget

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.templateapp.R
import com.example.templateapp.ui.adapter.SelectedAdapter
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.xuexiang.xutil.display.ScreenUtils

object BottomSheetMultiSelectDialog {

    fun getDialog(
        context: Context,
        dataList: Array<String>,
        isFullScreen: Boolean = false,
        listener: OnConfirmListener
    ): BottomSheetDialog {
        val dialog = BottomSheetDialog(context)
        val view =
            LayoutInflater.from(context).inflate(R.layout.dialog_bottom_sheet, null)


        val rv = view.findViewById<RecyclerView>(R.id.recyclerView)
        initDialogList(rv, context)

        val adapter = SelectedAdapter()
        rv.adapter = adapter
        adapter.refresh(dataList.toMutableList())

        val title = view.findViewById<TextView>(R.id.title)
        val cancelBtn = view.findViewById<TextView>(R.id.cancel)
        val confirmBtn = view.findViewById<TextView>(R.id.confirm)
        title.text = "选择分公司"
        cancelBtn.visibility = View.VISIBLE
        confirmBtn.visibility = View.VISIBLE

        cancelBtn.setOnClickListener { dialog.dismiss() }
        confirmBtn.setOnClickListener {
            listener.onConfirm(adapter.selectIdxs)
            dialog.dismiss()
        }

        if (isFullScreen) {
            dialog.behavior.peekHeight = ScreenUtils.getScreenHeight()
        }
        dialog.setContentView(view)

        dialog.delegate.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
            .also {
                it?.setBackgroundColor(Color.TRANSPARENT)
            }
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        return dialog
    }

    private fun initDialogList(
        recyclerView: RecyclerView,
        context: Context
    ) {
        val manager = LinearLayoutManager(context)
        manager.orientation = RecyclerView.VERTICAL
        recyclerView.layoutManager = manager

    }

    interface OnConfirmListener {
        fun onConfirm(selectIdxs: MutableSet<Int>)
    }
}